package rm.metrology.server;

import java.util.ArrayList;
import java.util.List;

import rm.metrology.shared.UserEntity;


public class UserDAO extends BaseDAO {

	private static final String SUPER_USER = "riyaz.mansoor@trade.gov.mv";
	
	private static final UserDAO fInstance = new UserDAO();
	
	public static final UserDAO getInstance() {
		return fInstance;
	}
	

	private boolean isCacheDirty = true;
	
	private List<UserEntity> fUsers = new ArrayList<UserEntity>();
	
	private UserDAO() {
	}
	
	public List<UserEntity> insert(UserEntity e) {
		validateAccess();
		validate(e);
		ofy().put(e);
		emailStaff("User Added", "<p/>User Details :<p/>" + e.toString());
		isCacheDirty = true;
		return selectAll();
	}
	
	public List<UserEntity> delete(Long id) {
		validateAccess();
		UserEntity eDB = ofy().get(UserEntity.class, id);
		ofy().delete(eDB);
		emailStaff("User Removed", "<p/>User Details :<p/>" + eDB.toString());
		isCacheDirty = true;
		return selectAll();
	}	
	
	public List<UserEntity> selectAll() {
		if (isCacheDirty) {
			fUsers.clear();
			fUsers.addAll(ofy().query(UserEntity.class).order("fCalibType").order("fRangeStart").list());
			isCacheDirty = false;
		}
		return fUsers;
	}
	
	public UserEntity getCurrent() {
		int index = fUsers.indexOf(getOperator());
		return (index < 0) ? null : fUsers.get(index);
	}

	private void validateAccess() {
		UserEntity user = getCurrent();
		if (SUPER_USER.equalsIgnoreCase(user.getStaff())) return; 
		validateNationalUser(user);
	}
	
}
